<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="primary" class="add" @click="addjs">添加角色</el-button>
      <el-table :data="list" border style="width: 100%" height="77vh">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['xia bdbottom', ind === 0 ? 'bdtop' : '']"
              v-for="(item1, ind) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag>{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  class="bdbottom cen"
                  v-for="item2 in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag type="success">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18" class="cen">
                    <el-tag
                      type="warning"
                      :class="['bdbottom', ind3 === 0 ? '' : '']"
                      v-for="(item3, ind3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightID(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="350">
          <template slot-scope="scope">
            <el-button
              size="small"
              icon="el-icon-edit"
              type="primary"
              round
              @click="edit(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="small"
              icon="el-icon-s-custom"
              type="warning"
              round
              @click="showRights(scope.row)"
              >分配权限</el-button
            >
            <el-button
              size="small"
              icon="el-icon-delete"
              type="danger"
              round
              @click="del(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色 -->
    <el-dialog
      title="添加角色"
      :visible.sync="adddialogVisible"
      @close="DialogClosed"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="ruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addjuese">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="bzdialogVisible"
      @close="DialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bzdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="bzjuese">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="setdialogFormVisible" @close="setdialog">
      <el-tree
        :data="rightslist"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        :props="defaultProps"
        ref="treeRef"
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="setsub"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [],
      rightslist: [],
      adddialogVisible: false,
      bzdialogVisible: false,
      setdialogFormVisible: false,
      defaultProps: {
        label: "authName",
        children: "children",
      },
      defkeys: [],
      roleId:'',
      ruleForm: {
        roleName: "",
        roleDesc: "",
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2~5 个字符", trigger: "blur" },
        ],
      },
      editForm: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async getList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取列表失败");
      }
      this.list = res.data;
    },
    addjs() {
      this.adddialogVisible = true;
    },
    //点击关闭时重置输入框
    DialogClosed() {
      this.$refs.ruleForm.resetFields();
    },
    addjuese() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;
        const { data: re } = await this.$http.post("roles", this.ruleForm);
        if (re.meta.status !== 201) {
          return this.$message.error("添加失败");
        }
        this.$message.success("添加成功");
        this.adddialogVisible = false;
        this.getList();
      });
    },
    //编辑
    async edit(id) {
      this.bzdialogVisible = true;
      const { data: res } = await this.$http.get(`roles/${id}`);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户信息失败");
      }
      this.editForm = res.data;
    },
    bzjuese() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;
        console.log(this.editForm);
        const { data: re } = await this.$http.put(
          "roles/" + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
          }
        );
        console.log(re);
        if (re.meta.status !== 200) {
          return this.$message.error("编辑失败");
        }
        this.$message.success("编辑成功");
        this.bzdialogVisible = false;
        this.getList();
      });
    },
    del(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`);
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败");
          }
          this.$message.success("删除成功");
          this.getList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //根据id移除权限 角色id 权限id
    removeRightID(role, rightId) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          console.log(role);
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败");
          }
          this.$message.success("删除成功");
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          role.children = res.data;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //展示分配权限
    async showRights(roles) {
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限失败");
      }
      this.rightslist = res.data;
      this.getLeafkeys(roles,this.defkeys)
      this.setdialogFormVisible = true;
      this.roleId = roles.id
    },
    // 监听对话框关闭
    setdialog(){
      this.defkeys = []
    },
    async setsub(){
      let keys = [this.$refs.treeRef.getCheckedKeys(),this.$refs.treeRef.getHalfCheckedKeys()]//获取全选和半选的节点
      let idStr = keys.join(',');
      const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr});
      if (res.meta.status !== 200) {
        return this.$message.error("权限分配失败");
      }
      this.$message.success("权限分配成功");
      this.getList();
      this.setdialogFormVisible = false;
    },
    getLeafkeys(node,arr){//node节点不包含children属性，就是三级节点
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item=>{
        this.getLeafkeys(item,arr)
      })
    }
  },
};
</script>
<style scoped>
.add {
  margin-bottom: 20px;
}
.xia {
  margin: 20px 50px;
  padding-top: 20px;
  display: flex;
  align-items: center;
}
.el-row {
  padding: 10px 0;
}
.el-tag {
  margin-right: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.cen {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
}
</style>